package com.bean;

import java.lang.reflect.Field;

/**
 * 不要改package路径和类名
 * @author zhoufang
 * @version v0.1 2019年7月9日 下午3:21:01  zhoufang
 */
public abstract class BaseModel {

	/** 指定主键 */
	public Object getPrimaryKey() {
		return null;
	}

	/**
	 * 指定复合索引,每个索引之间用#隔开
	 * @return
	 */
	public String[] getComplexIndexs() {
		return null;
	}
	
	public void setFieldValue(String fieldName, String value) {
		try {
			Class<?> superclass = getClass().getSuperclass();
			Field field = superclass.getDeclaredField(fieldName);
			field.setAccessible(true);
			Class<?> type = field.getType();
			if (type == int.class || type == Integer.class) {
				int parseDouble = (int) Double.parseDouble(value);
				field.set(this, parseDouble);
			} else if (type == long.class || type == Long.class) {
				long parseDouble = (long) Double.parseDouble(value);
				field.set(this, parseDouble);
			} else if (type == float.class || type == Float.class) {
				float parseDouble = (float) Double.parseDouble(value);
				field.set(this, parseDouble);
			} else if (type == double.class || type == Double.class) {
				double parseDouble = Double.parseDouble(value);
				field.set(this, parseDouble);
			} else if (type == boolean.class || type == Boolean.class) {
				boolean bool = Boolean.getBoolean(value);
				field.set(this, bool);
			} else if (type == String.class) {
				field.set(this, value);
			}
			field.setAccessible(false);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public Object getFieldValue(String fieldName) throws Exception {
		Class<? extends BaseModel> clazz = getClass();
		Field field = null;
		try {
			field = clazz.getDeclaredField(fieldName);
			field.setAccessible(true);
			return field.get(this);
		} catch (NoSuchFieldException e) {
			try {
				field = clazz.getSuperclass().getDeclaredField(fieldName);
				field.setAccessible(true);
				return field.get(this);
			} catch (NoSuchFieldException e1) {
				throw new NoSuchFieldException("class:" + getClass().getName() + "-----缺少字段:" + fieldName);
			}
		} catch (SecurityException e) {
			e.printStackTrace();
		} finally {
			field.setAccessible(false);
		}
		return null;
	}

}
